import { Product } from '../../types';
import { PRODUCTS } from '../../constants';

const STORAGE_KEY = 'abellaProducts';

// 获取商品数据
export const getProducts = (): Product[] => {
  const savedProducts = localStorage.getItem(STORAGE_KEY);
  if (savedProducts) {
    return JSON.parse(savedProducts);
  }
  // 首次加载时，将默认数据保存到本地存储
  localStorage.setItem(STORAGE_KEY, JSON.stringify(PRODUCTS));
  return PRODUCTS;
};

// 保存商品数据
export const saveProducts = (products: Product[]): void => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(products));
};

// 添加商品
export const addProduct = (product: Omit<Product, 'id'>): Product => {
  const products = getProducts();
  const newProduct: Product = {
    ...product,
    id: Date.now().toString()
  };
  const updatedProducts = [...products, newProduct];
  saveProducts(updatedProducts);
  return newProduct;
};

// 更新商品
export const updateProduct = (id: string, product: Partial<Product>): Product | null => {
  const products = getProducts();
  const index = products.findIndex(p => p.id === id);
  if (index === -1) {
    return null;
  }
  const updatedProduct = { ...products[index], ...product };
  const updatedProducts = [...products];
  updatedProducts[index] = updatedProduct;
  saveProducts(updatedProducts);
  return updatedProduct;
};

// 删除商品
export const deleteProduct = (id: string): boolean => {
  const products = getProducts();
  const updatedProducts = products.filter(p => p.id !== id);
  if (updatedProducts.length === products.length) {
    return false;
  }
  saveProducts(updatedProducts);
  return true;
};

// 获取单个商品
export const getProductById = (id: string): Product | null => {
  const products = getProducts();
  return products.find(p => p.id === id) || null;
};
